use-shallow-routing.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { useEffect, useRef } from 'react';
  2. import { useRouter } from 'next/router';
  3. import { isClient } from '@growi/core/dist/utils';
  4. import type { CommonEachProps } from '../common-props';
  5. /**
  6. * Custom hook for syncing pathname by Shallow Routing
  7. * Optimized to minimize unnecessary router operations and re-renders
  8. */
  9. export const useShallowRouting = (props: CommonEachProps): void => {
  10. const router = useRouter();
  11. const lastPathnameRef = useRef<string>();
  12. // Sync pathname by Shallow Routing with performance optimization
  13. useEffect(() => {
  14. if (!isClient() || !props.currentPathname) return;
  15. // Skip if pathname hasn't changed (prevents unnecessary operations)
  16. if (lastPathnameRef.current === props.currentPathname) return;
  17. const currentURL = decodeURI(window.location.pathname);
  18. // Only update if URLs actually differ
  19. if (currentURL !== props.currentPathname) {
  20. const { search, hash } = window.location;
  21. router.replace(`${props.currentPathname}${search}${hash}`, undefined, {
  22. shallow: true,
  23. });
  24. }
  25. // Update reference for next comparison
  26. lastPathnameRef.current = props.currentPathname;
  27. }, [props.currentPathname, router]);
  28. };